/**
 * @file main.c
 * @brief  serial demo
 *
 * Copyright (C) 2014 JakeYang <add358@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

#include "serial.h" 

pthread_mutex_t serial_mutex = PTHREAD_MUTEX_INITIALIZER;

static void *read_thread(void *arg);
static void *write_thread(void *arg);

int main(int argc, const char *argv[])
{
    Serial *serial = NULL;

    int i = 0;

    pthread_t pread;
    pthread_t pwrite;

    printf("open %s\n",argv[1]);
    serial = serial_open(argv[1]);
    if(NULL == serial) {
        fprintf(stderr, "Cannot open %s\n", argv[1]);
        return -1;
    }

    pthread_create(&pread, NULL, read_thread, serial);
    pthread_create(&pwrite, NULL, write_thread, serial);

    pthread_join(pread, NULL);
    pthread_join(pwrite, NULL);

    serial_close(serial);
    serial = NULL;

    return 0;
}

void *read_thread(void *arg)
{
    int len = 0;
    char buf[1024] = {0};
    Serial *serial = (Serial *)arg;
    int i;

    while (1) {
//	pthread_mutex_lock(&serial_mutex);
    len=serial_read(serial, buf, 10);
//	pthread_mutex_unlock(&serial_mutex);
        if (len < 0) {
            fprintf(stderr, "read failed\n");
            break;
        }

	buf[len] = 0;

	printf("%s", buf);

        if (0 == len) {
            sleep(1);
        }
    }
}

void *write_thread(void *arg)
{
    int len = 0;
    char c = 0;;
    Serial *serial = (Serial *)arg;
    int i;

    while (1) {
	c = getchar();
//	pthread_mutex_lock(&serial_mutex);
	len = serial_write(serial, &c, 1);
//	pthread_mutex_unlock(&serial_mutex);
	if (len < 0) {
		return NULL;
	}

//	printf("%c", c);

    }
}
